import {Component, OnInit} from '@angular/core';

import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd';
import {LoginService} from '../../../services/login.service';
import {setToken} from '../../../util/token.util';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  validateForm: FormGroup;

  constructor(private fb: FormBuilder, private message: NzMessageService, private loginService: LoginService) {
    this.loginService.routerRedirect();
  }

  // 登陆
  submitForm(): void {
    this.loginService.routerRedirect();

    for (const i of Object.keys(this.validateForm.controls)) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }

    const oauth2ClientInfo = this.loginService.getOauth2ClientInfo();
    oauth2ClientInfo.username = this.validateForm.controls.userName.value;
    oauth2ClientInfo.password = this.validateForm.controls.password.value;

    this.loginService.login(oauth2ClientInfo).subscribe(response => {
      this.message.success('登陆成功！');
      // 解构赋值 const {access_token, token_type} = Object.create(response);
      setToken(response.access_token, response.token_type);
      this.loginService.routerRedirect();
    }, error => {
      this.message.error(error.message);
    }, () => {
      console.log('ok');
    });
  }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      userName: ['admin', [Validators.required]],
      password: ['111', [Validators.required]],
      remember: [false]
    });
  }
}
